<script setup>
import router from "@/router/index.js";
import { ref } from "vue";
import {gsap} from "gsap";
import {onMounted} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import ChangePass from "@/views/User/components/changePass.vue";

// 发送axios请求
let config = {
  method: 'get',
  url: '/bind/question/get',
  baseURL: 'http://localhost:8080',
  params: {
    username: localStorage.getItem('forgetStore'),
  },
};

const que = ref({data: []});
let jwtToken = ref('');

onMounted(() => {
  async function fetchData() {
    try {
      // 使用await等待axios.get的响应
      const res = await axios(config);
      // 遍历res.data.data，将每个item的content添加到form.data中
      let count = 0;
      res.data.data.securityQuestions.forEach((item) => {
        item.answer=''
        que.value.data.push(item);
      });

    } catch (error) {
      // 打印错误信息
      console.error('Error fetching data:', error);
    }
  }
  fetchData();
})

let passwordFormVisible = ref(false)
// 返回忘记密码页面
const back = () => {
  router.push("/forget")
}

// 组件挂载时的动画效果
onMounted(() => {
  gsap.from(".cat", {
    delay:1,
    duration: 2,
    x: 0,
    y: -500,
    ease: "bounce.out",
  })})

// 猫猫移动动画
const catMove = () => {
  gsap.to(".cat", {
    keyframes: {
      x: [0,-200,-200],
      y: [0,0,800],
      rotate:[0,-90,0],
      ease:"bounce.out",
    },
    duration: 2,
    yoyo: true,
    repeat: 1,
  })
}

// 提交表单
const submit = () => {
  console.log(que.value.data)
  const formData = new FormData();
  formData.append('username', localStorage.getItem('forgetStore'));
  let count = 1;
  que.value.data.forEach((item) => {
    formData.append("question_id"+count, item.question_id)
    formData.append("answer"+count,item.answer)
    count++
  });
  console.log(formData)
  axios({
    method: 'post',
    url: '/bind/question/post',
    baseURL: 'http://localhost:8080',
    data: formData
  })
      .then((response) => {
          if(response.data.code === 104008){
            ElMessage({
              message: '验证失败！',
              type: 'warning',
              duration: 2000,
            })
          }
        else{
            passwordFormVisible.value = true;
            jwtToken = response.data.data.jwt_token;
            ElMessage({
              message: '验证成功,请修改密码！',
              type: 'success',
              duration: 2000,
            })
          }
      })
}
</script>

<template>
  <div class="flex justify-start items-start">
    <el-link class="iconfont icon-fanhui " :underline=false @click="back"></el-link>
    <div class="flex flex-col items-center justify-center mt-48">
      <img src="../../assets/icon/cat.png" alt="喵喵喵" class="cat" @click="catMove">
      <div>考考你！</div>
    </div>
    <div class="flex">
      <div class="flex flex-col items-center justify-center mt-32">
        <el-form :model="que" label-width="100px">
          <div v-for="item in que.data" :key="item.question_id" class="qa">
            <span>{{ item.question }}</span>
            <el-form-item label-width="0">
              <el-input v-model="item.answer" placeholder="是什么捏？" class="input"></el-input>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div class="flex flex-col items-end justify-end ml-8 mb-[18px]">
        <el-button type="primary" @click="submit">提交</el-button>
      </div>
    </div>
  </div>
  <changePass :isShow=passwordFormVisible :jwtToken=jwtToken></changePass>
</template>

<style scoped lang="scss">
.iconfont{
  font-size: 48px;
}
.qa{
  margin-top: 40px;
  display: flex;
  flex-direction: column;
  align-items: start;
  justify-content: space-between;
}
.input{
  width: 500px;
  margin-top: 30px;
}
</style>